//
//  TicketsViewController.m
//  NiuBanJin
//
//  Created by Billy on 15/10/10.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "TicketsViewController.h"
#import "TicketViewCell.h"
#import "BCSwitchView.h"
#import "Ticket.h"
#import "TicketExcahngeAndSigningController.h"
#import "RateDetailsController.h"

@interface TicketsViewController () <UITableViewDataSource,UITableViewDelegate,UITabBarDelegate,BCSwitchViewDelegate>

@property (nonatomic, strong) BCSwitchView *view_tickets; //加息券
@property (nonatomic, strong) UIView *view_header; //牛头像红背景

@property (nonatomic, strong) NSMutableArray *mutableArray_allTicketsData; //加息券数据源
@property (nonatomic, strong) NSMutableArray *mutableArray_data; // 年化收益

@property (nonatomic, strong) UITableView *tableView; //显示加息券内容

@property (nonatomic, copy)  NSString* str_page; //用于下拉刷新的判定是哪一页面 1:未使用 2: 已使用 3:已过期
@property (nonatomic, assign)  int pageNumber; //用于刷新的

@property (nonatomic, strong) NSDictionary *dic_params; //当前页面数据访问的参数集合

@property (nonatomic, strong) NSMutableDictionary *mutableDictionary_rate; //当前用户利率

@end

@implementation TicketsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self pageSettingsAndSubviewsCreation];

//    // 添加tableView刷新状态
    [self setupFresh];
}

- (void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.str_page = @"1";
    self.pageNumber = 1;
    [self buttonSelected:[self.view_tickets viewWithTag:100]]; //BUG 251,每次出现该页面，自动显示未使用的
    
    // 添加tableView刷新状态
    [self getDataFromServer];
}

#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    // 禁用主界面的返回按钮
    [self.navigationItem setLeftBarButtonItem:nil];
    [self.navigationItem setTitle:@"加息券"];
    [super setRightBarButtonItemTitle:@"兑换加息券" imageName:@"rightCorner" actionName:@selector(exchangeTicket)];// 右边item

    // subviews
    [self.view addSubview:self.view_header];
    [self.view addSubview:self.view_tickets];
    [self.view addSubview:self.tableView];
    
    //默认刷新未使用的加息券
    self.str_page = @"1"; // 默认显示1
    self.pageNumber = 1 ;
}

- (void) setupFresh {
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    
//    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}

#pragma mark - TableView datasource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    [self updateDataForHeaderView]; //当有新数据返回的时候更新头部数据
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.mutableArray_allTicketsData count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView setRowHeight:MULTIPLYHEIGHT(180.0/2)];
                             
    static NSString *identifer = @"cell" ;
    
    TicketViewCell *cell = (TicketViewCell *)[tableView dequeueReusableCellWithIdentifier:identifer];
    
    if (!cell) {
        
        cell = [[TicketViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifer];
    }

    if ([self.mutableArray_allTicketsData count] > 0) {

        cell.ticket =  self.mutableArray_allTicketsData[indexPath.row];
        
    }
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    Ticket *ticket =  self.mutableArray_allTicketsData[indexPath.row];
    
    if (![ticket.ticket_couponStatus isEqualToString:@"1"]) {
        
        return;
    }
    
    NSLog(@"当前的page:%d==%@",self.pageNumber, ticket.ticket_number_id);
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES]; //进度条
    
    NSDictionary *dic_params = @{@"token":[UserManager sharedUserManager].user.user_userToken,@"userId":[UserManager sharedUserManager].user.user_userId,@"id":ticket.ticket_number_id};
    
    [[NetworkUtil sharedNetworkUtil] zzjrUseTicketByParmeteres:dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if (!error) {  //没有网络错误
            
            // 开始解析数据
            NSDictionary *dic = parsedData;
            
            if([dic[@"status"] intValue] == 0) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:dic[@"result"][@"content"] message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                
                [alert show];
                
            } else {// 不是网络出错，是密码错 or 其它错误
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                
                [UsefulUtil showAlertView:dic[@"msg"]];
            }
        }else {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UsefulUtil showAlertView:error.description];
        }
    }];
}

- (void)updateDataForHeaderView {
    
    self.mutableDictionary_rate = [NSMutableDictionary dictionary];//每次重新初始化，保证数据最新
    
    if (self.mutableArray_data.count == 3) {
        
        // 收益显示: 基本+ 增加的
        if ([self.mutableArray_data[2] integerValue] ==0) {
        
            NSString *str_original = self.mutableArray_data[0];
            NSString *str_content = [NSString stringWithFormat:@"%@%%+0%%",str_original];
            
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str_content];
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:(iPhone4?30:40)] range:NSMakeRange(0, str_original.length)];  //8
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(str_original.length , 2)]; //%+
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:(iPhone4?30:40)] range:NSMakeRange(str_original.length + 2, 1)];
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(str_content.length-1, 1)];
            
             [(UILabel *)[self.view_header viewWithTag:20] setAttributedText:attrStr];
     
            [self.mutableDictionary_rate setObject:str_original forKey:@"rate"];
            [self.mutableDictionary_rate setObject:@"0" forKey:@"addingRate"];
            
        }else {
            
            NSString *str_original = self.mutableArray_data[0];
            NSString *str_adding = self.mutableArray_data[2];
            
            NSString *str_rate = [NSString stringWithFormat:@"%@%%+%@%%",str_original,str_adding];
            
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str_rate];
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:(iPhone4?30:40)] range:NSMakeRange(0, str_original.length)];//8
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(str_original.length , 2)]; //%+
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:(iPhone4?30:40)] range:NSMakeRange(str_original.length+2 , str_adding.length)]; //1
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(str_rate.length - 1, 1)]; //%
            
          [(UILabel *)[self.view_header viewWithTag:20] setAttributedText:attrStr];
            
            [self.mutableDictionary_rate setObject:str_original forKey:@"rate"];
            [self.mutableDictionary_rate setObject:str_adding forKey:@"addingRate"];
        }
        
        //到期提示,如果没使用，隐藏
        
        if (self.mutableArray_data[1]) {
            
            if (![self.mutableArray_data[1] isEqualToString:@"0"]) {
                
                [(UILabel *)[self.view_header viewWithTag:21] setText:[NSString stringWithFormat:@"当前年化收益持续时间至:  %@",self.mutableArray_data[1]]];
                
                [self.mutableDictionary_rate setObject:self.mutableArray_data[1] forKey:@"expiredDate"];
            }
            
        }else {
            
            [(UILabel *)[self.view_header viewWithTag:21] setHidden:YES];
        }
        
    }
}

#pragma mark - button event handling

//切换已使用/未使用 /已过期 ticket,选中状态要变成红色

- (void)buttonSelected:(UIButton *)button {
    
    UIView *tmp = [button.superview viewWithTag:200];
    
    dispatch_async(dispatch_get_main_queue(), ^{

        [UIView animateWithDuration:0.2 animations:^{
            
            tmp.frame = CGRectMake(button.frame.origin.x, tmp.frame.origin.y, tmp.bounds.size.width, tmp.bounds.size.height);
        } completion:^(BOOL finished) {
            
            [button setTitleColor:REDCOLOR forState:UIControlStateNormal];
        }];
    });
    
    //其它的button字体颜色要不变
    
    switch (button.tag) {

        case 100: //未使用
        {
            self.str_page  = @"1";
            self.pageNumber = 1;
            [self getDataFromServer];
            
            // 不选中的时候的颜色 ,好LOW的解决办法，为毛不用subview? 因为这个VC的VIEW太多了,笨
            
            [((UIButton *)[self.view_tickets viewWithTag:101]) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
            [((UIButton *)[self.view_tickets viewWithTag:102]) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
        }
            break;
            
        case 101: //已使用
        {
            self.str_page  = @"2";
            self.pageNumber = 1; //这儿把页数设为1的原因是防止全部点过上拉刷新，让pageNumber变成2， 这样的话进入存入点上拉刷新的话就会从3开始走,下面reason same
            [self getDataFromServer];
            
            // 不选中的时候的颜色
            
            [((UIButton *)[self.view_tickets viewWithTag:100]) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
            [((UIButton *)[self.view_tickets viewWithTag:102]) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
        }
            break;
        case 102: //已过期
        {
            self.str_page  = @"3";
            self.pageNumber = 1;
            [self getDataFromServer];
            
            // 不选中的时候的颜色
            
            [((UIButton *)[self.view_tickets viewWithTag:100]) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
            [((UIButton *)[self.view_tickets viewWithTag:101]) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
        }
            break;
            
        default:
            break;
    }
}

// 兑换规则
- (void) ticketUsageGuideButtonHandle: (UIButton *) button {
    
    [UsefulUtil showAlertView:@"这儿会链接一个H5网页来显示"];
    NSLog(@"动态h5页面显示");
    
}
// 兑换
- (void) exchangeTicket {
    
    TicketExcahngeAndSigningController *combineVC = [[TicketExcahngeAndSigningController alloc] init];;
    [combineVC setType:@"ticket"];
    [combineVC setHidesBottomBarWhenPushed:YES];
    
    [self.navigationController pushViewController:combineVC animated:YES];
}

#pragma mark - gesture handling

- (void) expiredDateDetails:(UITapGestureRecognizer *) tap {
    
    RateDetailsController *detailsVC = [[RateDetailsController alloc] init];

    [detailsVC setDic_rateInfo:self.mutableDictionary_rate];
    [detailsVC setHidesBottomBarWhenPushed:YES];
    
    [self.navigationController pushViewController:detailsVC animated:YES];
}

#pragma mark - data prepation

- (void) getDataFromServer {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [[NetworkUtil sharedNetworkUtil] zzjrGetTicketslistByParmeteres:[self getDic_params]transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
        NSLog(@"当前访问的参数是:%@",[self getDic_params]);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if (!error) {  //没有网络错误
            
            NSDictionary *dic_result = parsedData; //这个parsed 已经解析过了,key = ticketList 为所有的ticket数据
            
            // 因为有下拉刷新，所以这儿不能光想着clear ,按pageNumber来区分，如果大于2表明有下拉刷新要保存历史记录
        
            if (self.pageNumber > 1) { //保存历史数据
                
                [self.mutableArray_allTicketsData addObjectsFromArray: dic_result[@"ticketList"]];

            } else { // =1 的时候表明是第一次刷新
            
                // 清除历史数据
                
                [self.mutableArray_data removeAllObjects];
                [self.mutableArray_allTicketsData removeAllObjects];
                
                // 获得最新数据
                self.mutableArray_allTicketsData = dic_result[@"ticketList"]; //重新赋值
            
                if ([self.mutableArray_allTicketsData count] == 0) { //判定什么时候显示空数据几个字
                    
                    EmptyDataView *view_empty = [[EmptyDataView alloc]initWithFrame:self.tableView.frame];
                    [self.view addSubview:view_empty]; // 加过一次后就永远存在了，要想办法去掉
                    
                    self.pageNumber = 1; //BUG 238
                }else {
                    
                    [self.view bringSubviewToFront:self.tableView]; //把tableview放前面就行了，不用remove再加,省资源
                }
            }
            
            if (dic_result[@"baseRate"]) {
                
                [self.mutableArray_data addObject:dic_result[@"baseRate"]];
            }
            
            if (dic_result[@"expiredDate"]) {
                
                [self.mutableArray_data addObject:dic_result[@"expiredDate"]];
            }
            if (dic_result[@"ticketRate"]) {
                
                [self.mutableArray_data addObject:dic_result[@"ticketRate"]];
            }
            
            [self.tableView reloadData];
            
        }else {
            
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UsefulUtil showAlertView:error.description];
        }
    }];

}

#pragma mark - header refresh

- (void) headerRefresh {
    
    self.pageNumber = 1; //刷新恢复 成默认值
    [self getDataFromServer];
}

- (void) footerRefresh {
    
    if ([self.mutableArray_allTicketsData count] >= 50) {
        
        self.pageNumber++;
    }
    
    [self getDataFromServer];
}

#pragma mark - alert view delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        
        [self getDataFromServer];
    }
    
}
#pragma mark - setter methods

- (NSDictionary *) getDic_params {
    
    return  @{@"token":[UserManager sharedUserManager].user.user_userToken,@"offSet":[NSString stringWithFormat:@"%d",self.pageNumber],@"userId":[UserManager sharedUserManager].user.user_userId,@"couponStatus":self.str_page};
}

- (NSMutableArray *)mutableArray_data {
    
    if (!_mutableArray_data) {
        
        _mutableArray_data = [NSMutableArray array];
    }
    
    return _mutableArray_data;
}

- (NSMutableArray *)mutableArray_allTicketsData {
    
    if (!_mutableArray_allTicketsData) {
        
        _mutableArray_allTicketsData = [NSMutableArray array];
    }
    
    return  _mutableArray_allTicketsData;
}

- (UIView *)view_header {
    
    if (!_view_header) {
        
        _view_header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(220.0/2))];
        [_view_header.layer setContents:(__bridge id)([UIImage imageNamed:@"viewTop"].CGImage)];
        
        // 牛像
        CALayer *layer_cow = [self layerCreationWithFrame:CGRectMake(MULTIPLYWIDTH(26.0/2), MULTIPLYHEIGHT(30.0/2),MULTIPLYWIDTH(157.0/2), MULTIPLYHEIGHT(157.0/2)) andContents:(__bridge id)[UIImage imageNamed:@"cow"].CGImage];
        [_view_header.layer addSublayer:layer_cow];

        // 当前年化收益
        
        UILabel *label_ratePrompt = [UsefulUtil labelCreationWithFrame:CGRectMake(CGRectGetMaxX(layer_cow.frame) + MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(41.0/2), MULTIPLYWIDTH(220.0/2), MULTIPLYHEIGHT(34.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont boldSystemFontOfSize:15.0] text:@"当前年化收益:"];
       
        [_view_header addSubview:label_ratePrompt];

        // 真正的收益显示:
        
        UILabel *label_rateShown = [UsefulUtil labelCreationWithFrame:CGRectMake(CGRectGetMaxX(label_ratePrompt.frame) + MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(17.0/2), SCREEN_WIDTH - CGRectGetMaxX(label_ratePrompt.frame)-  MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(70.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont boldSystemFontOfSize:40.0] text:@"8%"];
        
        [label_rateShown setAdjustsFontSizeToFitWidth:NO];
        [label_rateShown setTag:20];
        
        [_view_header addSubview:label_rateShown];

        // 有效期 ,这儿加一个手势要能到另一页面
        
        UILabel *label_expiredDate = [UsefulUtil labelCreationWithFrame:CGRectMake(label_ratePrompt.frame.origin.x, CGRectGetMaxY(label_ratePrompt.frame) +MULTIPLYHEIGHT(37.0/4) , MULTIPLYWIDTH(400.0/2), MULTIPLYHEIGHT(44.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont boldSystemFontOfSize:11.0] text:@""];
        [_view_header addSubview:label_expiredDate];
        
        [label_expiredDate setTag:21];
        
        // 详情二个字
        
        UILabel *label_detail = [UsefulUtil labelCreationWithFrame:CGRectMake(CGRectGetMaxX(label_expiredDate.frame) + MULTIPLYWIDTH(10.0/2), label_expiredDate.frame.origin.y+MULTIPLYHEIGHT(10.0/2), MULTIPLYWIDTH(44.0/2), MULTIPLYHEIGHT(24.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont systemFontOfSize:11.0] text:@"详情"];

        [_view_header addSubview:label_detail];
        
        UIView *view_sep = [UsefulUtil viewCreationWithFrame:CGRectMake(label_detail.frame.origin.x, CGRectGetMaxY(label_detail.frame)+MULTIPLYHEIGHT(1.0/2), label_detail.bounds.size.width, MULTIPLYHEIGHT(1.0/2)) backgroundColor:[UIColor whiteColor] backGroundImage:nil];

        [_view_header addSubview:view_sep];
        
        // 手部加手势
        UITapGestureRecognizer *tap_details1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(expiredDateDetails:)];
        UITapGestureRecognizer *tap_details2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(expiredDateDetails:)];
        UITapGestureRecognizer *tap_details3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(expiredDateDetails:)];
        UITapGestureRecognizer *tap_details4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(expiredDateDetails:)];
        
        //统一加手势看详情:
        [label_detail setUserInteractionEnabled:YES];
        [label_expiredDate setUserInteractionEnabled:YES];
        [label_ratePrompt setUserInteractionEnabled:YES];
        [label_rateShown setUserInteractionEnabled:YES];
        
        [label_detail addGestureRecognizer:tap_details1];
        [label_expiredDate addGestureRecognizer:tap_details2];
        [label_ratePrompt addGestureRecognizer:tap_details3];
        [label_rateShown addGestureRecognizer:tap_details4];
        
        //获取方法和使用规则
        
        UIButton *button_usageGuide = [[UIButton alloc] initWithFrame:CGRectMake(label_expiredDate.frame.origin.x - 2.0, CGRectGetMaxY(label_expiredDate.frame) + MULTIPLYHEIGHT(23.0/2), MULTIPLYWIDTH(222.0/2), MULTIPLYHEIGHT(40.0/2))];
        
        [button_usageGuide addTarget:self action:@selector(ticketUsageGuideButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
        
        [button_usageGuide setBackgroundColor:[UIColor whiteColor]];
        [button_usageGuide setTitleColor:[UsefulUtil colorWithHexString:@"#fb4747"] forState:UIControlStateNormal];
        [button_usageGuide.titleLabel setFont:[UIFont systemFontOfSize:11.0]];
        [button_usageGuide.layer setCornerRadius:MULTIPLYHEIGHT(20.0/2)];
        [button_usageGuide setTitle:@"获取方法和使用规则" forState:UIControlStateNormal];
        [button_usageGuide.titleLabel setAdjustsFontSizeToFitWidth:YES];
        [_view_header addSubview:button_usageGuide];
    }
    
    return _view_header;
}

// 记得把这个方法收集起来

- (CALayer *) layerCreationWithFrame:(CGRect ) frame andContents:(id) content {
    
    CALayer *layer_tmp = [CALayer layer];
    [layer_tmp setFrame:frame];
    [layer_tmp setContents:content];
    
    return layer_tmp;
}

- (BCSwitchView *)view_tickets {
    
    if (!_view_tickets) {
        
        _view_tickets = [[BCSwitchView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_header.frame), SCREEN_WIDTH, MULTIPLYHEIGHT(90.0/2)) Items:@[@"未使用",@"已使用",@"已过期"] scrollColor:[UIColor redColor]];
        [_view_tickets setDelegate:self];
    }
    
    return  _view_tickets;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_tickets.frame), SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(self.view_tickets.frame) ) style:UITableViewStylePlain];

        [_tableView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setBackgroundColor:BASECOLOR];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
    }
    
    return  _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
